import * as http from 'http'
import * as querystring from 'querystring'

//必须调用end()
export default {
	get(url: string, data?: any) {
		return new Promise((resolve, reject) => {
			const options = {
				host: 'localhost',
				path: data ? url + '?' + querystring.stringify(data) : url,
				port: 80,
				method: 'GET',
			}
			//发送请求
			const req = http.request(options, function (res) {
				let body = ''
				res.setEncoding('utf-8')
				res.on('data', function (chunk) {
					body += chunk
				})
				res.on('end', function () {
					resolve(JSON.parse(body))
				})
			})
			req.end()
			console.log('get ' + options.path)
		})
	},
	//
	post(url: string, data?: any) {
		return new Promise((resolve, reject) => {
			const contents = querystring.stringify(data)
			const options = {
				host: 'localhost',
				path: url,
				port: 80,
				method: 'POST',
				headers: {
					'Content-Type': 'application/x-www-form-urlencoded',
					'Content-Length': contents.length,
				},
			}
			//发送请求
			const req = http.request(options, function (res) {
				let body = ''
				res.setEncoding('utf-8')
				res.on('data', function (chunk) {
					body += chunk
				})
				res.on('end', function () {
					resolve(JSON.parse(body))
				})
			})
			req.write(contents)
			req.end()
			console.log('post ' + url + ' params-> ' + contents)
		})
	},
}
